// 导入数据库连接
import { getDB } from '../db/connection.js';

// 定义并导出所有模型
class Component {
  static async getAll() {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM components');
    return rows;
  }

  static async getById(id) {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM components WHERE id = ?', [id]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async getByName(name) {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM components WHERE name = ?', [name]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async create(name, description) {
    const db = await getDB();
    const [result] = await db.execute(
      'INSERT INTO components (name, description) VALUES (?, ?)',
      [name, description]
    );
    return result.insertId;
  }

  static async update(id, data) {
    const db = await getDB();
    const fields = Object.keys(data);
    const values = Object.values(data);
    const setClause = fields.map(field => `${field} = ?`).join(', ');
    
    await db.execute(
      `UPDATE components SET ${setClause} WHERE id = ?`,
      [...values, id]
    );
    
    return this.getById(id);
  }

  static async delete(id) {
    const db = await getDB();
    await db.execute('DELETE FROM components WHERE id = ?', [id]);
  }
}

class ComponentVersion {
  static async getAll() {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM component_versions');
    return rows;
  }

  static async getById(id) {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM component_versions WHERE id = ?', [id]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async getByComponentId(componentId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM component_versions WHERE component_id = ? ORDER BY created_at DESC',
      [componentId]
    );
    return rows;
  }

  static async getActiveByComponentId(componentId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM component_versions WHERE component_id = ? AND is_active = true',
      [componentId]
    );
    return rows.length > 0 ? rows[0] : null;
  }

  static async create(componentId, version, content, isActive = false) {
    const db = await getDB();
    const [result] = await db.execute(
      'INSERT INTO component_versions (component_id, version, content, is_active) VALUES (?, ?, ?, ?)',
      [componentId, version, JSON.stringify(content), isActive]
    );
    return result.insertId;
  }

  static async update(id, data) {
    const db = await getDB();
    const fields = Object.keys(data);
    const values = Object.values(data);
    const setClause = fields.map(field => `${field} = ?`).join(', ');
    
    await db.execute(
      `UPDATE component_versions SET ${setClause} WHERE id = ?`,
      [...values, id]
    );
    
    return this.getById(id);
  }

  static async setActive(id, isActive) {
    const db = await getDB();
    await db.execute(
      'UPDATE component_versions SET is_active = ? WHERE id = ?',
      [isActive, id]
    );
    
    return this.getById(id);
  }

  static async delete(id) {
    const db = await getDB();
    await db.execute('DELETE FROM component_versions WHERE id = ?', [id]);
  }
}

class GrayRelease {
  static async getAll() {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM gray_releases');
    return rows;
  }

  static async getById(id) {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM gray_releases WHERE id = ?', [id]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async getByComponentVersionId(componentVersionId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM gray_releases WHERE component_version_id = ?',
      [componentVersionId]
    );
    return rows;
  }

  static async getActiveReleases() {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM gray_releases WHERE status = ?',
      ['active']
    );
    return rows;
  }

  static async create(componentVersionId, threshold, percentage = 100.00, status = 'pending') {
    const db = await getDB();
    const [result] = await db.execute(
      'INSERT INTO gray_releases (component_version_id, threshold, percentage, status) VALUES (?, ?, ?, ?)',
      [componentVersionId, threshold, percentage, status]
    );
    return result.insertId;
  }

  static async update(id, data) {
    const db = await getDB();
    const fields = Object.keys(data);
    const values = Object.values(data);
    const setClause = fields.map(field => `${field} = ?`).join(', ');
    
    await db.execute(
      `UPDATE gray_releases SET ${setClause} WHERE id = ?`,
      [...values, id]
    );
    
    return this.getById(id);
  }

  static async setStatus(id, status) {
    const db = await getDB();
    await db.execute(
      'UPDATE gray_releases SET status = ? WHERE id = ?',
      [status, id]
    );
    
    return this.getById(id);
  }

  static async delete(id) {
    const db = await getDB();
    await db.execute('DELETE FROM gray_releases WHERE id = ?', [id]);
  }
}

class UserUpdate {
  static async getAll() {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM user_updates');
    return rows;
  }

  static async getById(id) {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM user_updates WHERE id = ?', [id]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async getByUserId(userId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM user_updates WHERE user_id = ? ORDER BY updated_at DESC',
      [userId]
    );
    return rows;
  }

  static async getByComponentVersionId(componentVersionId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM user_updates WHERE component_version_id = ?',
      [componentVersionId]
    );
    return rows;
  }

  static async create(userId, componentVersionId, success = true) {
    const db = await getDB();
    const [result] = await db.execute(
      'INSERT INTO user_updates (user_id, component_version_id, success) VALUES (?, ?, ?)',
      [userId, componentVersionId, success]
    );
    return result.insertId;
  }

  static async delete(id) {
    const db = await getDB();
    await db.execute('DELETE FROM user_updates WHERE id = ?', [id]);
  }

  static async deleteByUserIdAndComponentVersionId(userId, componentVersionId) {
    const db = await getDB();
    await db.execute(
      'DELETE FROM user_updates WHERE user_id = ? AND component_version_id = ?',
      [userId, componentVersionId]
    );
  }
}

class UserVisit {
  static async getByUserIdAndComponentId(userId, componentId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM user_visits WHERE user_id = ? AND component_id = ?',
      [userId, componentId]
    );
    return rows.length > 0 ? rows[0] : null;
  }

  static async recordVisit(userId, componentId) {
    const db = await getDB();
    const existingVisit = await this.getByUserIdAndComponentId(userId, componentId);
    
    if (existingVisit) {
      await db.execute(
        'UPDATE user_visits SET visit_count = visit_count + 1, last_visited_at = NOW() WHERE id = ?',
        [existingVisit.id]
      );
      return existingVisit.id;
    } else {
      const [result] = await db.execute(
        'INSERT INTO user_visits (user_id, component_id, visit_count) VALUES (?, ?, 1)',
        [userId, componentId]
      );
      return result.insertId;
    }
  }

  static async resetVisitCount(userId, componentId) {
    const db = await getDB();
    await db.execute(
      'UPDATE user_visits SET visit_count = 0 WHERE user_id = ? AND component_id = ?',
      [userId, componentId]
    );
  }

  static async delete(userId, componentId) {
    const db = await getDB();
    await db.execute(
      'DELETE FROM user_visits WHERE user_id = ? AND component_id = ?',
      [userId, componentId]
    );
  }
}

// 导出所有模型
export {
  Component,
  ComponentVersion,
  GrayRelease,
  UserUpdate,
  UserVisit
};
